<?php

use Phalcon\Di\FactoryDefault\Cli as CliDI;
use Phalcon\Cli\Console as ConsoleApp;
use Phalcon\Loader;
use Phalcon\Db;
use Phalcon\Db\Adapter\Pdo\Mysql as DbAdapter;
use Phalcon\Queue\Beanstalk;

ini_set('date.timezone', 'Asia/Shanghai');


// 使用CLI工厂类作为默认的服务容器
$di = new CliDI();

//日志目录
define('BASE_PATH', dirname(__DIR__));
define('APP_PATH', BASE_PATH . '/../app');

define('LOG_PATH', BASE_PATH . '/../logs/');

define('PUBLIC_PATH', BASE_PATH . '/../public');


/**
 * 注册类自动加载器
 */
$loader = new Loader();

$loader->registerDirs(
    [
        __DIR__ . '/task',
        __DIR__ . '/../tasks',
        APP_PATH . '/library',
        APP_PATH . '/controllers',
        APP_PATH . '/config',
        APP_PATH . '/models',
        APP_PATH . '/views',
    ]
);

$loader->register();

//vendor

require __DIR__ . '/../../vendor/autoload.php';

// 加载配置文件（如果存在）

$configFile = APP_PATH . '/config/config.php';

if (is_readable($configFile)) {
    $config = include $configFile;
    $di->set("config", $config);
    $di->set('db', function () use ($config) {
        return new DbAdapter($config->database->toArray());
    });

    $di->set('redis', function (){
        $redis = new Redis();
        $redis->connect('127.0.0.1');
        return $redis;
    });
}


// 创建console应用
$console = new ConsoleApp();
$di->setShared("console", $console);
$console->setDI($di);


/**
 * 处理console应用参数
 */
$arguments = [];

foreach ($argv as $k => $arg) {
    if ($k === 1) {
        $arguments['task'] = $arg;
    } elseif ($k === 2) {
        $arguments['action'] = $arg;
    } elseif ($k >= 3) {
        $arguments['params'][] = $arg;
    }
}


try {
    // 处理参数
    $console->handle($arguments);
} catch (\Phalcon\Exception $e) {
    echo $e->getMessage();

    exit(255);
}